import java.util.PriorityQueue;

//创建一个类来描述任务（至少包括任务内容和时间）
class MyTimerTask implements Comparable<MyTimerTask> {
    private Runnable runnable;
    private long time;
    public MyTimerTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }
    public Runnable getRunnable() {
        return this.runnable;
    }
    public long getTime() {
        return this.time;
    }
    public int compareTo(MyTimerTask o) {
        //返回执行时间最小的一个任务
        return (int)(this.time - o.time);
    }
}

class MyTimer {
    //创建一个优先级队列,来保存当前的任务
    private PriorityQueue<MyTimerTask>  queue = new PriorityQueue<>();
    //锁对象
    private Object locker = new Object();

    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            queue.offer(new MyTimerTask(runnable, delay));
            locker.notify();
        }
    }

    public MyTimer() {
        //创建一个扫描线程，进行反复不停地进行扫描，直到到执行时间
        Thread t = new Thread(() -> {
          while(true) {
              try {
                  synchronized (locker) {
                      while(queue.isEmpty()) {
                          locker.wait();
                      }
                      //获取当前队列中的最小时间任务
                      MyTimerTask task = queue.peek();
                      //获取当前系统的时间
                      long curTime = System.currentTimeMillis();
                      if(curTime >= task.getTime()) {
                          task.getRunnable().run();
                          queue.poll();
                      }else {
                          locker.wait(task.getTime() - curTime);
                      }
                  }
              }catch (InterruptedException e) {
                  e.printStackTrace();

              }
          }
        });
        t.start();
    }

}


public class test3 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        },3000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        }, 2000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("4000");
            }
        },4000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        },1000);
        System.out.println("程序启动！！");
    }
}